package org.takeback.chat.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.takeback.chat.entity.GcRoom;
import org.takeback.chat.service.RoomService;
import org.takeback.chat.store.room.Room;
import org.takeback.chat.store.room.RoomStore;
import org.takeback.chat.store.user.UserStore;
import org.takeback.mvc.ResponseUtils;
import org.takeback.util.annotation.AuthPassport;

@Controller
@RequestMapping({ "/room" })
public class RoomConcactor {
	@Autowired
	private RoomService roomService;
	@Autowired
	private RoomStore roomStore;
	@Autowired
	private UserStore userStore;
	private final Lock lock = new ReentrantLock();

	@RequestMapping(value = { "/{id}" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public ModelAndView getRoom(@PathVariable String id) {
		Room room = (Room) this.roomStore.get(id);
		if (room == null) {
			return ResponseUtils.jsonView(404, "房间" + id + "不存在.");
		}
		return ResponseUtils.jsonView(200, "success", room);
	}

	@RequestMapping(value = { "/authorize" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public ModelAndView validatePassword(@RequestBody Map<String, String> params) {
		String roomId = (String) params.get("roomId");
		String password = (String) params.get("password");
		Room room = (Room) this.roomStore.get(roomId);
		if (room == null) {
			return ResponseUtils.jsonView(404, "房间" + roomId + "不存在.");
		}
		if ((!room.isNeedPsw().booleanValue()) || (password.equals(room.getPsw()))) {
			return ResponseUtils.jsonView(200, "success");
		}
		return ResponseUtils.jsonView(401, "incorrect password");
	}

	@RequestMapping({ "/join/{id}" })
	public ModelAndView joinIn(@PathVariable String id, HttpServletRequest request) {
		Room room = (Room) this.roomStore.get(id);
		if (room == null) {
			return ResponseUtils.jsonView(404, "房间" + id + "不存在.");
		}
		String lastRoomId = (String) WebUtils.getSessionAttribute(request, "roomId");
		if (lastRoomId != null) {
			WebUtils.setSessionAttribute(request, "lastRoomId", lastRoomId);
		}
		WebUtils.setSessionAttribute(request, "roomId", id);
		Object o = WebUtils.getSessionAttribute(request, "$uid");
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "$uid");
		if (uid != null) {
			try {
				this.lock.lock();
				if (room.getPosition().intValue() >= room.getLimitNum().intValue()) {
					return ResponseUtils.jsonView(530, "房间已满.");
				}
			} finally {
				this.lock.unlock();
			}
		}
		Object body = Maps.newHashMap();
		((Map) body).put("room", room);
		((Map) body).put("uid", uid);
		return ResponseUtils.jsonView(200, "success", body);
	}

	@RequestMapping({ "/list/{pageNo}" })
	public ModelAndView rooms(@PathVariable Integer pageNo, HttpServletRequest request) {
		String s = "";
		Map<String, Object> params = Maps.newHashMap();
		String cata = request.getParameter("cata");
		String type = request.getParameter("type");
		if (!StringUtils.isEmpty(cata)) {
			s = " and a.catalog = :p";
			params.put("p", cata);
		}
		if (!StringUtils.isEmpty(type)) {
			s = " and a.type = :p";
			params.put("p", type);
		}
		List<GcRoom> rooms = this.roomService.findByHql(
				"from GcRoom a where a.status !='9'" + s + " order by a.hot desc, a.createdate desc", params, 100,
				pageNo.intValue());
		if ((rooms == null) || (rooms.size() == 0)) {
			return ResponseUtils.jsonView(new ArrayList());
		}
		List<Room> result = Lists.newArrayList();
		for (GcRoom room : rooms) {
			result.add(this.roomStore.get(room.getId()));
		}
		for (Room room : result) {
			if ("G022".equals(room.getType())) {
				room.setName2(room.getName().substring(0, 4));
				room.setDesc(room.getName().substring(4));
			} else if ("G04".equals(room.getType())) {
				if(room.getName().contains("包")) {
					String roomName = room.getName();
					int index = roomName.indexOf("包") > -1 ? roomName.indexOf("包"): 4;
					String str = room.getName().substring(index - 2, index);
					if(isNumeric(str)) {
						room.setName2(roomName.substring(0, roomName.indexOf("包") - 2));
						room.setDesc(room.getName().substring(roomName.indexOf("包") - 2));
					} else {
						room.setName2(roomName.substring(0, roomName.indexOf("包") - 1));
						room.setDesc(room.getName().substring(roomName.indexOf("包") - 1));
					}
				} else {
					room.setName2(room.getName());
				}
				
			}
		}
		return ResponseUtils.jsonView(result);
	}

	public boolean isNumeric(String str) {
		for (int i = 0; i < str.length(); i++) {
			System.out.println(str.charAt(i));
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	@AuthPassport
	@RequestMapping({ "/members/{id}" })
	public ModelAndView members(@PathVariable String id) {
		Room room = (Room) this.roomStore.get(id);
		if (room == null) {
			return ResponseUtils.jsonView(Lists.newArrayList());
		}
		return ResponseUtils.jsonView(room.getUsers().values());
	}

	@AuthPassport
	@RequestMapping(value = { "/props" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public ModelAndView getRoomProps(@RequestParam String roomId, HttpServletRequest request) {
		if (StringUtils.isBlank(roomId)) {
			roomId = (String) WebUtils.getSessionAttribute(request, "roomId");
		}
		Room room = (Room) this.roomStore.get(roomId);
		if (room == null) {
			return ResponseUtils.jsonView(404, "房间" + roomId + "不存在.");
		}
		Map<String, Object> res = new HashMap();
		res.put("room", this.roomService.get(GcRoom.class, roomId));
		res.put("props", this.roomService.getRoomProps(roomId));
		return ResponseUtils.jsonView(res);
	}
}
